package com.ykw.parking.controller;

import com.ykw.parking.Utils.Md5;
import com.ykw.parking.Utils.RandomId;
import com.ykw.parking.mapper.UserMapper;
import com.ykw.parking.pojo1.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;

@Controller
public class RegisterController {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    UserMapper userMapper;
    @PostMapping(value = "/toregister")
    public String Register(String username, String email, String Verification,String phone_number,
                           String password, Model model , HttpSession session){
        User user = userMapper.queryUserbyname(username);
        if(user!=null){
            model.addAttribute("msg1","用户名已存在!");
            return "register";
        }
        User user1 = userMapper.queryUserbyemail(email);
        if (user1!=null){
            model.addAttribute("msg1","邮箱已存在!");
            return "register";
        }
        long time= System.currentTimeMillis();
        long expiration = (long)session.getAttribute("Expiration");
        if(time-expiration>180000){
            model.addAttribute("msg1","验证码失效");
            return "register";
        }
        if (!Verification.equals(session.getAttribute("Verification"))){
            model.addAttribute("msg1","验证码错误");
            return "register";
        }
        String id= RandomId.getRandomNumberByNum(16);
        String password1= Md5.code(password);
        userMapper.insertUser1(id,username,phone_number,password1,email,0);
        model.addAttribute("msg1","注册成功");
        SimpleDateFormat sdf=new SimpleDateFormat("MM-dd");
        java.util.Date date=new java.util.Date();
        String str=sdf.format(date);
        redisTemplate.opsForHash().increment("user",str,1);
        return "login";
    }
}

